package com.homework.newsapp.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.homework.newsapp.R
import com.homework.newsapp.adapter.TabLayoutAdapter
import com.homework.newsapp.data.*
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class NewsFragment : Fragment(), TabLayout.OnTabSelectedListener {
    private var mView: View? = null
    private var mViewPager: ViewPager? = null
    private var newsListFragment = mutableListOf<Fragment>()

    private var newsChannelData: ArrayList<String>? = ArrayList()
    private var newsChannel: NewsChannel? = null

    private var tabLayout: TabLayout? = null
    private val NewsChannelCompleted = 0
    private val NewsChannelHander: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            //    super.handleMessage(msg)
            if (msg.what == NewsChannelCompleted) {

                for (x in 0 until 7) {
                    tabLayout!!.addTab(
                        tabLayout!!.newTab().setText(newsChannelData?.get(x).toString())
                    )
                    newsListFragment.add(NewsListFragment(newsChannelData?.get(x).toString()))
                }
                tabLayout?.setupWithViewPager(mViewPager)
                mViewPager!!.adapter = TabLayoutAdapter(newsListFragment!!, childFragmentManager)
                mViewPager!!.addOnPageChangeListener(
                    TabLayout.TabLayoutOnPageChangeListener(
                        tabLayout
                    )
                )
                for (x in 0 until 7) {
                    tabLayout!!.getTabAt(x)?.text = newsChannelData!!.get(x).toString()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        mView = inflater.inflate(R.layout.fragment_news_layout, container, false)
        newsListInit(mView!!)
        return mView
    }

    private fun getChannelData() {
        val okHttpClient = OkHttpClient()
            val url = getNewsChannel()
            val request = Request.Builder().url(url).build()
            okHttpClient.newCall(request).enqueue(object : okhttp3.Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Log.i("MyNewsApp", "getChannelData failure" + e.message.toString())
                }

                override fun onResponse(call: Call, response: Response) {
                    val json = response.body!!.string()
                    newsChannel = Gson().fromJson(json, NewsChannel::class.java)
                    val msg = Message()
                    if (newsChannel?.status == 0) {
                     //   Log.i("MyNewsApp", "getChannelData success" + newsChannel?.result.toString())
                        newsChannelData = newsChannel!!.result
                        msg.what = NewsChannelCompleted
                        NewsChannelHander.sendMessage(msg)
                    } else {
                        Log.i("MyNewsApp", newsChannel?.msg)
                    }
                }
        })
    }

    private fun newsListInit(view: View) {
        getChannelData()
        mViewPager = view.findViewById(R.id.ViewPagerContent)
        tabLayout = view.findViewById(R.id.TabLayout)
    }

    override fun onTabReselected(p0: TabLayout.Tab?) {
        TODO("Not yet implemented")
    }

    override fun onTabUnselected(p0: TabLayout.Tab?) {
        TODO("Not yet implemented")
    }

    override fun onTabSelected(p0: TabLayout.Tab?) {
        mViewPager?.currentItem = p0!!.position
    }
}